package com.webwork.lims.system.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webwork.lims.system.dao.AuthorityDao;
import com.webwork.lims.system.dao.MenuDao;
import com.webwork.lims.system.dataobject.Authority;
import com.webwork.lims.system.dataobject.Menu;
import com.webwork.lims.system.dataobject.Role;
import com.webwork.lims.system.service.MenuService;
import com.webwork.lims.util.Paging;

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private AuthorityDao authDao;
	
	@Override
	public List<Menu> query(Menu menu) {
		return this.query(menu, new Paging(0, 0));
	}
	
	@Override
	public List<Menu> query(Menu menu, Paging page) {
		return menuDao.query(menu, page.getCurrPage(), page.getPageSize());
	}
	
	@Override
	public int count(Menu menu) {
		return menuDao.count(menu);
	}
	
	@Override
	public Menu get(String menuCode) {
		Menu queryObj = new Menu();
		queryObj.setMenuCode(menuCode);
		List<Menu> menu = this.query(queryObj);
		if (menu != null && menu.size() > 0) {
			if (menu.size() > 1) {
				System.out.println("存在不止一条记录!");
			} else {
				return menu.get(0);
			}
		} else {
			System.out.println("找不到该菜单!");
		}
		return null;
	}

	@Override
	public List<Menu> getMenuByRole(Role role) {
		Authority queryObj = new Authority();
		queryObj.setRole(role);
		List<Authority> list = authDao.query(queryObj, 0, 0);
		List<Menu> ret = new ArrayList<Menu>();
		for (Authority auth : list) {
			ret.add(this.get(auth.getMenuCode()));
		}
		Collections.sort(ret, new Comparator<Menu>() {
			@Override
			public int compare(Menu o1, Menu o2) {
				return o1.getMenuOrder() - o2.getMenuOrder();
			}
		});
 
		return ret;
	}

	@Override
	public void delete(String menuCode) {
		menuDao.delete(menuCode);
	}

	@Override
	public void save(Menu menu) {
		if (this.get(menu.getMenuCode()) != null) {
			menuDao.update(menu);
		} else {
			menuDao.insert(menu);
		}
	}

}
